package com.smart.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.auth.dto.MemberDto;
import com.smart.auth.jwt.JwtTokenUtils;
import com.smart.common.utils.ResponseUtils;
import com.smart.common.vo.ResponseResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * jwt 工具类
 * 生成 token
 * 验证 token
 * 获取认证用户信息  uid  username
 */


/**
 * 登录成功的处理
 * 返回令牌
 * jwt
 * http://127.0.0.1:9050/login
 */
@Component
public class SmartAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    ObjectMapper objectMapper;
    @Resource
    JwtTokenUtils jwtToken;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //  登录成功之后通过用户信息生成token 返回给客服端
        //  客服端携带token获取用户信息
        MemberDto member = (MemberDto) authentication.getPrincipal();
        String token = jwtToken.createToken(member);
        ResponseUtils.responseToJson(httpServletResponse, objectMapper.writeValueAsString(ResponseResult.success(token)));
    }
}
